# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exporters import JsonItemExporter


class GuoxuedashiPipeline:

    def __init__(self):
        self.buffer = []

    def process_item(self, item, spider):
        self.buffer.append(item)
        return item

    def close_spider(self, spider):
        if self.buffer:
            with open('output.json', 'wb') as json_file:
                exporter = JsonItemExporter(json_file, indent=4, ensure_ascii=False)
                exporter.start_exporting()
                for item in self.buffer:
                    exporter.export_item(item)
                exporter.finish_exporting()
        # 清空
        self.buffer.clear()